package com.lianjia.sh.se.esb.server.log;
import com.lianjia.sh.se.esb.server.action.MessageAction;
import com.lianjia.sh.se.esb.server.annotation.MessageActionCfg;
import com.lianjia.sh.se.esb.spi.model.Message;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeoutException;

/**
 * 由于listener中需要拦截的方法是内容调用，无法通过真正的aop拦截
 * 同时，spring 4.2.6不支持配置exposeProxy，因此改为注册回调方式实现
 * @author yangjiangping
 * @since 2016-07-18 16:20
 */
@Component
public class MessageLogInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageLogInterceptor.class);

    @Autowired
    MessageLogService messageLogService;
    @Autowired
    MessageLogRepeatService messageLogRepeatService;

    /**
     * 处理消息前记录日志
     *
     * @author yangjiangping
     * @since 2016-07-20 11:30
     */
    public void beforeExecuteMessage(MessageAction messageAction,Message message) {
        MessageActionCfg messageActionCfg = messageAction.getClass().getAnnotation(MessageActionCfg.class);
        String actionType = messageActionCfg.actionType();
        int errMaxRepeatCnt = messageActionCfg.errMaxRepeatCnt();
        messageLogService.insert(message,actionType,errMaxRepeatCnt);
    }

    /**
     * 执行失败记录日志
     * @param messageAction
     * @param message
     */
    public void afterExecuteMessageFail(MessageAction messageAction,Message message) {
        //更新发送成功标识
        messageLogRepeatService.updateRepeatSuccess(message);
    }

    /**
     * 执行成功记录日志
     * @param messageAction
     * @param message
     */
    public void afterExecuteMessageSuccess(MessageAction messageAction,Message message) {
        MessageActionCfg messageActionCfg = messageAction.getClass().getAnnotation(MessageActionCfg.class);
        String actionType = messageActionCfg.actionType();
        int errMaxRepeatCnt = messageActionCfg.errMaxRepeatCnt();
        //异步记录异常日志
        messageLogRepeatService.insertOrUpdateRepeatFail(message,actionType,errMaxRepeatCnt);
    }
}
